package org.kuaishou.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Cookie;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class CookieFileUtil {
    public static void saveCookiesToFile(Set<Cookie> cookies, String filePath) throws Exception {
        String string = JSON.toJSONString(cookies, true);
        File file = FileUtils.getFile(filePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            boolean mkdirs = parentFile.mkdirs();
            if (!mkdirs) throw new Exception("创建Cookie目录异常：" + parentFile.getAbsolutePath());
        }
        FileUtils.writeStringToFile(file, string, "UTF-8");
    }

    public static Set<Cookie> loadCookiesFromFile(String filePath) throws IOException {
        File file = FileUtils.getFile(filePath);
        if (!file.exists()) return new HashSet<>();
        String toString = FileUtils.readFileToString(file, "UTF-8");
        Set<Cookie> cookies = JSON.parseObject(toString, new TypeReference<Set<Cookie>>() {
        });
        return cookies;
    }

}
